import { useEffect, useState } from 'react'
import { List, Card, Button, Modal, Form, Input, message } from 'antd'
import { discussionService } from '../../services'
import { useSelector } from 'react-redux'
import { RootState } from '../../store'

const Discussion = () => {
  const [discussions, setDiscussions] = useState([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [form] = Form.useForm()
  const { isAuthenticated } = useSelector((state: RootState) => state.auth)

  useEffect(() => {
    loadDiscussions()
  }, [])

  const loadDiscussions = async () => {
    try {
      setLoading(true)
      const response: any = await discussionService.getDiscussions()
      if (response.code === 200) {
        setDiscussions(response.data.discussions)
      }
    } catch (error) {
      console.error('Load discussions error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async (values: any) => {
    try {
      const response: any = await discussionService.createDiscussion(values)
      if (response.code === 201) {
        message.success('发布成功!')
        setModalVisible(false)
        form.resetFields()
        loadDiscussions()
      }
    } catch (error) {
      console.error('Create discussion error:', error)
    }
  }

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>讨论区</h1>
        {isAuthenticated && (
          <Button type="primary" onClick={() => setModalVisible(true)}>
            发起讨论
          </Button>
        )}
      </div>

      <List
        loading={loading}
        dataSource={discussions}
        renderItem={(discussion: any) => (
          <Card style={{ marginBottom: '16px' }}>
            <h3>{discussion.title}</h3>
            <div dangerouslySetInnerHTML={{ __html: discussion.content.substring(0, 200) + '...' }} />
            <div style={{ marginTop: '16px', color: '#999' }}>
              <span>作者: {discussion.user.username}</span>
              <span style={{ marginLeft: '16px' }}>浏览: {discussion.views}</span>
              <span style={{ marginLeft: '16px' }}>回复: {discussion._count?.replies || 0}</span>
            </div>
          </Card>
        )}
      />

      <Modal
        title="发起讨论"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <Form form={form} onFinish={handleCreate}>
          <Form.Item
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="标题" />
          </Form.Item>
          <Form.Item
            name="content"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <Input.TextArea rows={6} placeholder="内容" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              发布
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Discussion
